package com.rahwi.rahwi_server.Service.impl;

import com.rahwi.rahwi_server.DAO.*;
import com.rahwi.rahwi_server.DefineEntity.*;
import com.rahwi.rahwi_server.Entity.*;
import com.rahwi.rahwi_server.vo.data.DetailReply;
import com.rahwi.rahwi_server.vo.params.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName PostDetailService
 * @Description
 * @Date 2021/12/26 1:49
 * @Autor dn
 */
@Service
public class PostDetailService {

    @Autowired
    private PostDAO postDAO;

    @Autowired
    private CommentDAO commentDAO;

    @Autowired
    private ReplyDAO replyDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private PostLikeDAO postLikeDAO;

    @Autowired
    private CommentLikeDAO commentLikeDAO;

    /**
     * @param \postId , pageParam, only?
     * @return number
     * 返回帖子详情页面的所有信息
     * @Date 2021/12/26 3:20
     * @Autor dn
     * @Version 1.0
     */
    public PostDetail GetPostDetail(int postId, PageParams pageParams ,int uid, boolean onlyOwner) {
        PostDetail postDetail = new PostDetail();
        //查询该帖子名下所有楼
        Specification<Comment> specification = (Specification<Comment>)
                (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("Pid"), postId);
        PageRequest pageable = PageRequest.of(pageParams.getPage()-1, pageParams.getSize());
        List<Comment> commentList = commentDAO.findAll(specification,pageable).getContent();  //分页查询所有楼信息
        postDetail.setTotalPage(commentDAO.findAll().size()/pageParams.getSize());
        if(commentDAO.findAll().size()%pageParams.getSize()>0) postDetail.setTotalPage(postDetail.getTotalPage() + 1);    //该贴的回复楼数
        User owner = userDAO.getOne(postDAO.findById(postId).get().getUid());   // 楼主
        List<PostData> postDataList = new ArrayList<>();
        System.out.println("commentList:" + commentList.size());
        for(Comment comment: commentList){
            PostData postData = new PostData();
            postData.setUserId(comment.getUid());
            User user = userDAO.findById(comment.getUid()).get();
            postData.setUser_nickname(user.getUserName());
            postData.setUser_photo(user.getPicture());
            postData.setId(comment.getCid());
            postData.setContent(comment.getDetail());
            String[] s = {comment.getPicture()};
            postData.setImages(s);
            postData.setPosition(comment.getPosition());
            postData.setCreated_at(comment.getDateTime());
            if(comment.getUid() == owner.getUserId()) postData.setIs_owner(true);    // 这个楼是不是楼主本人发的
            if(comment.getUid() == 1) postData.setIs_post_by_admin(true);    // 默认管理员账号ID为1  // 这个楼是不是管理员发的
            if(uid == 1 || uid == comment.getUid() || uid == owner.getUserId()) postData.setIs_post_by_admin(true);    //有没有删除权限 如果当前的登陆用 户是楼主、层主或管理员就返回true
            //  TODO

//            int like_num = 0; //该楼的点赞数量
            Specification<CommentLike> commentLikeSpecification = (Specification<CommentLike>) (root, criteriaQuery, criteriaBuilder)
                    ->criteriaBuilder.and(criteriaBuilder.equal(root.get("Cid"), comment.getCid()),criteriaBuilder.equal(root.get("Uid"), uid));
            if(commentLikeDAO.findAll(commentLikeSpecification).size()>0)
                postData.setIs_voted(true);//            boolean is_voted = false; //现在浏览网页的用户是否点过赞
            Specification<CommentLike> commentLikeNumber = (Specification<CommentLike>) (root, criteriaQuery, criteriaBuilder)
                    ->criteriaBuilder.equal(root.get("Cid"),comment.getCid());
            postData.setLike_num(commentLikeDAO.findAll(commentLikeNumber).size());
            List<DetailReply> detailReplyList = new ArrayList<>();
            Specification<Reply> Replyspecification = (Specification<Reply>)
                    (root, criteriaQuery, criteriaBuilder) ->
                            criteriaBuilder.equal(root.get("CommentId"), comment.getCid());
            PageRequest replyPageable = PageRequest.of(0, 10);
            List<Reply> replyList = replyDAO.findAll(Replyspecification,replyPageable).getContent(); //该楼所有回复信息
            postData.setAllpage(replyList.size()/10 + replyList.size()%10==0?0:1); //楼中楼评论的总页数 楼中楼评 论一页默认10个
            postData.setCurrent(1);//楼中楼评论的当前页数，默认返回1
            postData.setReply_num(replyList.size());//回复总数量
            System.out.println("该楼的回复信息："+ replyList.size());
            for(Reply reply: replyList){
                DetailReply detailReply = new DetailReply();
                detailReply.setId(reply.getRid());
                //设置发送者属性
                Specification<User> SenderDataSpecification = (Specification<User>)
                        (root, criteriaQuery, criteriaBuilder) ->
                                criteriaBuilder.equal(root.get("UserId"), reply.getSenderId());
                User sender = userDAO.findAll(SenderDataSpecification).get(0);
                detailReply.setUser_id(reply.getSenderId());
                detailReply.setUser_nickname(sender.getUserName());
                detailReply.setUser_photo(sender.getPicture());

                //设置接收者属性
                Specification<User> ReceiverDataSpecification = (Specification<User>)
                        (root, criteriaQuery, criteriaBuilder) ->
                                criteriaBuilder.equal(root.get("UserId"), reply.getReceiverId());
                User receiver = userDAO.findAll(ReceiverDataSpecification).get(0);
                detailReply.setTo_user_id(reply.getReceiverId());
                detailReply.setTo_user_nickname(receiver.getUserName());
                detailReply.setComment_user_id(comment.getUid());
                detailReply.setCreated_at(reply.getDateTime());
                detailReply.setContent(reply.getContent());
                detailReplyList.add(detailReply);
            }
            postData.setReplies(detailReplyList);
            postDataList.add(postData);
        }
        postDetail.setList(postDataList);
        System.out.println("postDetail:" + postDetail.getTotalPage() + ":::" + postDetail.getList().size());
        return postDetail;
    }

    /**
     * @param postId , userid
     * @return isloved
     * 收藏帖子
     * @Date 2021/12/26 16:22
     * @Autor dn
     * @Version 1.0
     */
    public boolean LikePost(int postId,int uid){
        Specification<PostLike> specification = (Specification<PostLike>) (root, criteriaQuery, criteriaBuilder)
                ->criteriaBuilder.and(criteriaBuilder.equal(root.get("Pid"), postId),criteriaBuilder.equal(root.get("Uid"), uid));
        if(postLikeDAO.findAll(specification).size()>0){
            postLikeDAO.delete(postLikeDAO.getOne(postLikeDAO.findAll(specification).get(0).getId()));
            return false;
        }
        else {
            PostLike postLike = new PostLike();postLike.setPid(postId);postLike.setUid(uid);
            postLikeDAO.save(postLike);
            return true;
        }
    }

    /**
     * @param \cid , uid
     * @return boolean
     * 点赞楼层
     * @Date 2021/12/29 16：18
     * @Autor dn
     * @Version 1.0
     */
    public boolean LikeComment(int commentId,int uid){
        Specification<CommentLike> specification = (Specification<CommentLike>) (root, criteriaQuery, criteriaBuilder)
                ->criteriaBuilder.and(criteriaBuilder.equal(root.get("Cid"), commentId),criteriaBuilder.equal(root.get("Uid"), uid));

        if(commentLikeDAO.findAll(specification).size()>0){
            commentLikeDAO.delete(commentLikeDAO.getOne(commentLikeDAO.findAll(specification).get(0).getId()));
            return false;
        }
        else {
            CommentLike commentLike = new CommentLike();commentLike.setCid(commentId);commentLike.setUid(uid);
            commentLikeDAO.save(commentLike);
            return true;
        }
    }

    /**
     * @param \pid
     * @return postDetail
     * 主楼信息
     * @Date 2021/12/29 16：18
     * @Autor dn
     * @Version 1.0
     */
    public MainPostDetail GetPostDetail(int pid){
        MainPostDetail mainPostDetail = new MainPostDetail();
        Post post;
        User user;
        try{
            post = postDAO.getOne(pid);
            user = userDAO.getOne(post.getUid());
        }catch(javax.persistence.EntityNotFoundException e){
            return null;
        }
        mainPostDetail.setIs_post_by_admin(user.getUserId()==1?true:false);//这个楼是不是管理员发的(楼主是不是管 理员)
        String[] image = {post.getPicture()};
        mainPostDetail.setImages(image);
        mainPostDetail.setContent(post.getContent());
        mainPostDetail.setTitle(post.getTitle());
        mainPostDetail.setCreated_at(post.getTime()); //时间
        mainPostDetail.setId(pid);//主楼id

        mainPostDetail.setUser_photo(user.getPicture());//楼主头像
        mainPostDetail.setUser_nickname(user.getUserName());//楼主名称
        mainPostDetail.setDelete_private(user.getUserId()==1||user.getUserId()==post.getUid()?true:false);//有没有删除权限 如果当前的登陆用户 是楼主或管理员就返回true
        mainPostDetail.setIs_admin(user.getUserId()==1?true:false);//楼主是否是管理员

        Specification<PostLike> specification = (Specification<PostLike>) (root, criteriaQuery, criteriaBuilder)
                ->criteriaBuilder.and(criteriaBuilder.equal(root.get("Pid"), pid),criteriaBuilder.equal(root.get("Uid"), user.getUserId()));
        mainPostDetail.setIs_voted(postLikeDAO.findAll(specification).size()>0?true:false);//是否点赞
        mainPostDetail.setIs_collected(postLikeDAO.findAll(specification).size()>0?true:false);//是否收藏
        Specification<PostLike> likeNumber = (Specification<PostLike>) (root, criteriaQuery, criteriaBuilder)
                ->criteriaBuilder.equal(root.get("Pid"), pid);
        mainPostDetail.setLike_count(postLikeDAO.findAll(likeNumber).size());//点赞个数
        //TODO
//        boolean is_official = false; //是否是官方贴 这就是一个帖子的属性而 已，管理员可以设置官方贴和加精
//        boolean isElite = false; //是否是精华帖
        return mainPostDetail;
    }

    /**
     * @param \cid pageParams
     * @return replys
     * 楼中楼回复
     * @Date 2021/12/29 17：48
     * @Autor dn
     * @Version 1.0
     */
    public ReplyDetail GetReplies(int page, int pagesize, int cid){
        ReplyDetail replyDetail = new ReplyDetail();
        List<ReplyData> replyDataList = new ArrayList<>();

        Specification<Reply> specification = (Specification<Reply>)
                (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("CommentId"), cid);
        PageRequest pageable = PageRequest.of(page-1, pagesize);
        List<Reply> replyList = replyDAO.findAll(specification,pageable).getContent();  //分页查询所有楼信息

        for(Reply reply : replyList) {
            ReplyData replyData = new ReplyData();
            replyData.setId(reply.getRid());//该评论的id
            replyData.setUser_id(reply.getSenderId());//发评论的人的id
            replyData.setUser_photo(userDAO.findById(reply.getSenderId()).get().getPicture()); //发评论的人头像
            replyData.setUser_nickname(userDAO.findById(reply.getSenderId()).get().getUserName());//发评论的人的名称
            replyData.setTo_user_id(reply.getReceiverId()); //回复对象的id
            replyData.setTo_user_nickname(userDAO.findById(reply.getReceiverId()).get().getUserName());//回复对象的名称 如果是给层主回复可以为空
            replyData.setComment_user_id(commentDAO.findById(cid).get().getUid());// 如果to_user_id==comment_user_id 代 表是给层主回复 如果不相等代表是给楼中楼的评论回复
            replyData.setCreated_at(reply.getDateTime());//发送时间
            replyData.setContent(reply.getContent()); //内容
            replyDataList.add(replyData);
        }

        replyDetail.setReplies(replyDataList);
        replyDetail.setPage(page);
        int size = replyDAO.findAll(specification).size()%pagesize;
        if (size >0)
            replyDetail.setTotalPage(replyDAO.findAll(specification).size()/pagesize + 1);
        else
            replyDetail.setTotalPage(replyDAO.findAll(specification).size()/pagesize);

        return replyDetail;
    }

}
